// pages/start/start.js
import NumberAnimate from '../../utils/NumberAnimate';
const app = getApp(); 
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //初始关口编号
  num:1,
  //最大关口编号
  maxNum:50,
  j: 1,//帧动画初始图片
  isSpeaking: false,//是否正在说话
  voices: [],//音频数组
  startRecTimeStamp: 0,
  stopRecTimeStamp: 0,
  silkFilePath:'',
  disable_sound_btn:false,
  cur_openid:'',
  //我的历史最高通关记录
  maxCount:1,
  //通关累积次数
  passedCount:0,
  //所有关口信息
  passes:null,
  //当前关口内容
  record: '汤上塔,塔滑汤,汤烫塔',
  showModalStatus: false,
  //临时存储文件名称
  fileName:'',
  isNum:2,
  //显示加载框
  showLoad:false,
  //滚动得分初始值
  scoreAnimation:0,
  //获得相似度后的实际得分
  score:40
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that=this
    app.getUserInfos()
    app.getUserInfo()
    console.log('当前用户openid:' + app.globalData.openid)
    that.data.cur_openid = app.globalData.openid
    wx.request({
      url: 'https://wsh.weyifeng.com/getPassInfo',
      method:'POST',
      header: { 'Content-Type':'application/x-www-form-urlencoded'},
      data: {challenger_openid:app.globalData.openid},
      success:function(res){
          console.log('加载关口信息如下:')
          console.log(res.data)
          if(res.data.success){
            that.setData({
              passes: res.data.passes,
              maxNum: res.data.passes.length,
              record: res.data.passes[0].passContent
            })
          }
      },fail:function(res){
        wx.showToast({
          title: '加载关口信息失败……',
          icon:'loading',
          duration:5000
        })
      }
    })
    wx.request({
      url: 'https://wsh.weyifeng.com/getMaxPassedRecord',
      method: 'post',
      data: {
        challenger_openid: app.globalData.openid,
        challenger_nickName: app.globalData.userInfo.nickName
      },
      header: { 'Content-Type': 'application/x-www-form-urlencoded' },
      success: function (res) {
        console.log('获取历史最高纪录返回结果:')
        console.log(res.data)
        if (res.data.success) {
          that.setData({
            maxCount: res.data.maxRecord.passedCount
          })
        }
      }, fail: function (data) {
        console.log('onShow获取最高历史记录失败……')
      }, complete: function (res) {
        console.log('onShow获取最高历史记录的请求完成!')
      }

    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (options) {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var that=this
    wx.request({
      url: 'https://wsh.weyifeng.com/getMaxPassedRecord',
      method: 'post',
      data: {
        challenger_openid: that.data.cur_openid,
        challenger_nickName: app.globalData.userInfo.nickName,
        passedCount: that.data.passedCount
      },
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      success: function (data) {
        console.log(data)
      },
      fail: function (res) {
        console.log('存储新记录失败')
      }, complete: function (res) {
        console.log('请求存储新纪录完成!')
      }
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }, 
  //手指按下
  touchdown: function () {
    console.log("开始录音...")
    var that = this
    var startTime = Date.parse(new Date())
    that.setData({
      startRecTimeStamp: startTime
    })
    
    speaking.call(this);
    that.setData({
      isSpeaking: true
    })
    //开始录音
    wx.startRecord({
      success: function (res) {
        //临时路径,下次进入小程序时无法正常使用
       wx.showLoading({
         title: '溜溜溜666……',
          mask: true
        })
        var tempFilePath = res.tempFilePath
        console.log("tempFilePath: " + tempFilePath)
        console.log('截取后的字符串:' + tempFilePath.substr(9))
        that.setData({
          silkFilePath: tempFilePath,
          fileName: tempFilePath ? tempFilePath.substr(9):''
        })
        //持久保存
       /*wx.saveFile({
          tempFilePath: tempFilePath,
          success: function (res) {
            //持久路径
            //本地文件存储的大小限制为 100M
            var savedFilePath = res.savedFilePath
            console.log("savedFilePath: " + savedFilePath)
            that.setData({
              silkFilePath: savedFilePath,
              fileName:savedFilePath?savedFilePath.substr(9):''
            })
          }
        })*/
        //获取录音音频列表
        /*
        wx.getSavedFileList({
          success: function (res) {
            var voices = [];
            for (var i = 0; i < res.fileList.length; i++) {
              //格式化时间
              var createTime = new Date(res.fileList[i].createTime)
              //将音频大小B转为KB
              var size = (res.fileList[i].size / 1024).toFixed(2);
              var voice = { filePath: res.fileList[i].filePath, createTime: createTime, size: size };
              console.log("文件路径: " + res.fileList[i].filePath)
              console.log("文件时间: " + createTime)
              console.log("文件大小: " + size)
              voices = voices.concat(voice);
            }
            that.setData({
              voices: voices
            })
          }
        })*/
        
      },
      fail: function (res) {
        //录音失败
        wx.showModal({
          title: '提示',
          content: '录音失败!'
        })
      },complete:function(res){
        /*wx.showToast({
          title: '录音结束',
          icon:'success',
          mask:true,
          duration:2000
        })
        wx.hideLoading()
        */
        console.log('录音完成')
      }
    })
  },
  //手指抬起
  touchup: function () {
    wx.stopRecord()
   var stopTime = Date.parse(new Date())
    console.log("录音结束...")
    /*wx.showLoading({
      title: '语音识别中……',
      mask: true
    })*/
    var that = this 
    that.setData({
      isSpeaking: false,
      stopRecTimeStamp: stopTime,
      score:0
    })
    clearInterval(this.timer)
   
    setTimeout(function () {
      //录音时长,单位:秒
      var recSeconds = (stopTime - that.data.startRecTimeStamp) / 1000
      console.log('录音用时：'+recSeconds+'秒')
      if (recSeconds < 2) {
        wx.showToast({
          title: '语音时间太短',
          icon: 'loading',
          duration: 2000
        })
        that.data.disable_sound_btn=false
      } else if (recSeconds > 60) {
        wx.showToast({
          title: '语音时长不得超过60秒',
          icon: 'loading',
          duration: 2000
        })
      
      } else if (!that.data.silkFilePath) {
        console.log('语音无法识别,文件存储路径为:' + that.data.silkFilePath)
        wx.showToast({
          title: '语音无法识别,请重试',
          icon: 'loading',
          duration: 2000
        })
       
      } else {
        wx.hideLoading()
        that.data.scoreAnimation=0
        that.setData({
          showLoad:true
        })
        var n1 = new NumberAnimate({
          from: 100,//最大值,累加到最大值停止
          speed: 50000,// 总时间
          refreshTime: 500,//  刷新一次的时间
          decimals:0,//小数点后的位数
          onUpdate: () => {//更新回调函数
            that.setData({
              scoreAnimation: n1.tempValue
            })
          },
          onComplete: () => {//完成回调函数
            that.setData({
              scoreComplete: '完成了' 
            })
          }
        })
        var upstartTime=Date.parse(new Date())
        var orderNo = parseInt(Math.random() * Math.pow(10, 15))
        that.data.disable_sound_btn = true
        console.log('订单号:' + orderNo + ',接收者openid：' + that.data.cur_openid+',文件临时路径:' + that.data.silkFilePath)
        if (orderNo) {
          var reqUrl = 'https://wsh.weyifeng.com/uploadSilk';
          wx.uploadFile({
            url: reqUrl,
            filePath: that.data.silkFilePath,
            name: 'file',
            formData: {
              orderNo: orderNo,
              receiver_openid: that.data.cur_openid,
              fileName:that.data.fileName,
              passId: that.data.num,
              sourceTxt:that.data.record
            },
            header: {
              'content-type': 'multipart/form-data'
            },
            success: function (res) {
              var str = res.data;
              var data = JSON.parse(str);
              console.log('存储silk文件返回的结果:')
              console.log(data)
              var upEndtime = Date.parse(new Date())
              console.log('上传silk文件用时:' + ((upEndtime - upstartTime) / 1000) + '秒')
              var finalScore=0
              if(data.similar){
                finalScore=parseInt(data.similar*100+'')
              }else{
                if (that.data.scoreAnimation<60){
                  finalScore = that.data.scoreAnimation
                }
              }
              that.setData({
                showLoad: false
              })
              n1=null
              n1 = new NumberAnimate({
                from: 1,//最大值,累加到最大值停止
                speed: 100,// 总时间
                refreshTime: 100,//  刷新一次的时间
                decimals: 0,//小数点后的位数
                onUpdate: () => {//更新回调函数
                  that.setData({
                    scoreAnimation: n1.tempValue
                  })
                },
                onComplete: () => {//完成回调函数
                  that.setData({
                    scoreComplete: '完成了'
                  })
                }
              })
              if (data.success) {
                
                if(data.similar>=0.6){
                  //通关成功
                  that.setData({
                    score: parseInt(data.similar * 100)
                  })
                  that.util2("open", 1)
                  var nextNum = that.data.num + 1
                  var maxNum = that.data.maxNum

                  if (nextNum <= maxNum) {
                    var new_passedCount = that.data.passedCount + 1
                    wx.request({
                      url: 'https://wsh.weyifeng.com/savePassedRecord',
                      method:'post',
                      data:{
                        challenger_openid:that.data.cur_openid,
                        challenger_nickName:app.globalData.userInfo.nickName,
                        passedCount: new_passedCount
                      },
                      header: { 'content-type': 'application/x-www-form-urlencoded'},
                      success:function(data){
                        console.log(data)
                      },
                      fail:function(res){
                        console.log('存储新记录失败')
                      },complete:function(res){
                        console.log('请求存储新纪录完成!')
                      }
                    })
                    //页面数据跳到下一关
                    that.setData({
                      num: nextNum,
                      record: that.data.passes[nextNum - 1].passContent,
                      passedCount: new_passedCount
                    })
                    //判断通关(是否为VIP并付钱)
                    if (nextNum >=4 && app.globalData.isVip != '1'){
                      wx.showModal({
                        content: '只能免费说前三哦。支付1元，可以使用本程序所有功能，是否支付？',
                        cancelText: '否',
                        confirmText: '是',
                        success: function (res) {
                          if (res.confirm) {
                            app.vipPay()
                            console.log('用户点击确定')
                          } else if (res.cancel) {
                            console.log('用户点击取消')
                            nextNum=nextNum-1
                            that.setData({
                              num: nextNum,
                              record: that.data.passes[nextNum - 1].passContent,
                              passedCount: new_passedCount
                            })
                          }
                        }
                      })
                    }
                  } else {
                    that.setData({
                      score: parseInt(data.similar * 100 + '')
                    })
                    wx.request({
                      url: 'https://wsh.weyifeng.com/savePassedRecord',
                      method: 'post',
                      data: {
                        challenger_openid: that.data.cur_openid,
                        challenger_nickName: app.globalData.userInfo.nickName,
                        passedCount: that.data.passes.length
                      },
                      header: { 'content-type': 'application/x-www-form-urlencoded' },
                      success: function (data) {
                        console.log(data)
                      },
                      fail: function (res) {
                        console.log('存储新记录失败')
                      }, complete: function (res) {
                        console.log('请求存储新纪录完成!')
                      }
                    })
                    wx.showToast({
                      title: '666,恭喜亲已全部K.O.',
                      icon: 'success',
                      duration: 3000
                    })
                  }
                }else{
                  //通关失败
                  if(data.similar>=0.4){
                    that.setData({
                      score: parseInt(data.similar * 100+'')
                    })
                  }else{
                    that.setData({
                      score: 40
                    })
                  }
                  that.util2("open", 0)
                }
              } else {
                wx.hideLoading()
                that.setData({
                  score: 30
                })
                n1=null
                n1 = new NumberAnimate({
                  from: that.data.scoreAnimation >= 60 ? 50: that.data.scoreAnimation,//最大值,累加到最大值停止
                  speed: 500,// 总时间
                  refreshTime: 500,//  刷新一次的时间
                  decimals: 0,//小数点后的位数
                  onUpdate: () => {//更新回调函数
                    that.setData({
                      scoreAnimation: n1.tempValue
                    })
                  },
                  onComplete: () => {//完成回调函数
                    that.setData({
                      scoreComplete: '完成了'
                    })
                  }
                })
                that.util2("open", 0)
                /*wx.showModal({
                  title: '提示',
                  content: data.msg,
                })*/
                console.log('语音识别返回结果:')
                console.log(res.data)
              }
            },
            fail: function (res) {
              console.log('录音失败,返回结果:')
              console.log(res)
              wx.showModal({
                title: '提示',
                content: "网络请求失败，请确保网络是否正常",
                showCancel: false,
                success: function (res) {
                  console.log('点击了确定按钮')
                  that.data.disable_sound_btn =false
                }
              })
            },
            complete: function (res) {
              that.setData({
                showLoad: false
              })
              that.data.disable_sound_btn = false
              console.log('录音完成,返回结果:')
              console.log(res)
              wx.hideLoading()

            }
          })
        }
      }
    }, 5000)
  },
  //点击播放录音

  gotoPlay: function (e) {
    var filePath = e.currentTarget.dataset.key;
    //点击开始播放

    wx.showToast({
      title: '开始播放',
      icon: 'success',
      duration: 1000
    })
    wx.playVoice({
      filePath: filePath,
      success: function () {
        wx.showToast({
          title: '播放结束',
          icon: 'success',
          duration: 1000
        })
      }
    })
  },
  //显示模态框
  powerDrawer: function (e) {
    var currentStatu = e.currentTarget.dataset.statu;
    this.util2(currentStatu,2)
  },
  util2: function (currentStatu,num) {
    /* 动画部分 */
    // 第1步：创建动画实例 
    var animation = wx.createAnimation({
      duration: 200, //动画时长 
      timingFunction: "linear", //线性 
      delay: 0 //0则不延迟 
    });

    // 第2步：这个动画实例赋给当前的动画实例 
    this.animation = animation;

    // 第3步：执行第一组动画 
    animation.opacity(0).rotateX(-100).step();

    // 第4步：导出动画对象赋给数据对象储存 
    this.setData({
      animationData: animation.export()
    })

    // 第5步：设置定时器到指定时候后，执行第二组动画 
    setTimeout(function () {
      // 执行第二组动画 
      animation.opacity(1).rotateX(0).step();
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象 
      this.setData({
        animationData: animation
      })

      //关闭 
      if (currentStatu == "close") {
        this.setData(
          {
            showModalStatus: false
          }
        );
      }
    }.bind(this), 200)

    // 显示 
    if (currentStatu == "open") {
      this.setData(
        {
          showModalStatus: true
        }
      );
    }

    if(num == 0){
      this.setData(
        {
          isNum: 0
        }
      );
    }

    if (num == 1) {
      this.setData(
        {
          isNum: 1
        }
      );
    }
  } 
})

//麦克风帧动画
function speaking() {
  var _this = this;
  //话筒帧动画
  var i = 1;
  this.timer = setInterval(function () {
    i++;
    i = i % 5;
    _this.setData({
      j: i
    })
  }, 200);
}